<template>
  <div ref="chartRef" :id="id" :class="className" :style="{ height: height, width: width }" />
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, shallowRef, ref, watch, nextTick } from "vue"
import * as echarts from 'echarts'

// 修复1: const 拼写错误
const props = withDefaults(defineProps<{
  className?: string
  id?: string
  width?: string
  height?: string
  options?: any
}>(), {
  className: 'chart',
  id: 'chart',
  width: '95%',
  height: '95%',
  options: () => ({})
})

// 修复2: 正确定义变量
const chartRef = ref<HTMLElement>() // DOM引用
const chart = shallowRef<echarts.ECharts>() // ECharts实例

// 修复3: 正确的初始化函数
function initChart() {
  if (!chartRef.value) return
  
  // 如果已存在实例，先销毁
  if (chart.value) {
    chart.value.dispose()
  }
  
  // 初始化echart实例
  chart.value = echarts.init(chartRef.value)
  chart.value.setOption(props.options, true)
  
  // 添加窗口大小变化监听
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小变化
function handleResize() {
  if (chart.value) {
    chart.value.resize()
  }
}

// 修复4: 添加options监听
watch(
  () => props.options,
  (newOptions) => {
    if (chart.value && newOptions) {
      chart.value.setOption(newOptions, true)
    }
  },
  { deep: true }
)

onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

onUnmounted(() => {
  // 修复5: 正确的清理
  if (chart.value) {
    chart.value.dispose()
    chart.value = null
  }
  window.removeEventListener('resize', handleResize)
})

// 暴露chart实例给父组件使用
defineExpose({
  chart
})
</script>

<style scoped>
.chart {
  width: 100%;
  height: 100%;
}
</style>
